<template>
    <div class="search">
        <div class="search-box">
            <form action="/">
                <van-search v-model="searchvalue" show-action placeholder="请输入搜索关键词" @search="onSearch" @cancel="onCancel" />
            </form>
        </div>
        <div class="search-history" v-if="historylist.list.length != 0">
            <div class="history-header">
                <p>最近搜索</p>
                <i @click="allClear"></i>
            </div>
            <div class="history-list">
                <ul>
                    <li v-for="item in historylist.list" @click="gethot">{{ item }}</li>
                </ul>
            </div>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { getSearchList } from "../../api/index";
import { ref, reactive } from "vue";
import { useStore } from "../../store/index";
import { useRouter, useRoute } from "vue-router";
import { showToast } from "vant";

let router = useRouter();
let route = useRoute();
const $store = useStore();

let searchvalue = ref("");
let flag = ref(false);

let historylist = reactive({
    list: [],
});

const gethot = (e: any) => {
    // console.log(e.target.innerText);
    searchvalue.value = e.target.innerText;
    onSearch();
};

const onSearch = () => {
    $store.getSearchVal(searchvalue.value);
    router.push({
        name: "searchlist",
    });
};

const allClear = () => {
    historylist.list = [];
    localStorage.removeItem("history");
};

const gethistory = () => {
    let history = localStorage.history;
    if (history != undefined) {
        let arr = history.split(",");
        historylist.list = arr;
    }
};
gethistory();

const onCancel = () => {
    router.push({
        path: "/",
    });
};
</script>

<style lang="scss" scoped>
.search-history {
    padding: 10px 10px;
    width: 100%;
    .history-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding-bottom: 15px;

        p {
            font-size: 16px;
            color: #313131;
        }

        i {
            display: block;
            width: 20px;
            height: 20px;
            background-image: url(@/assets/delete.png);
            background-repeat: no-repeat;
            background-size: 100%;
        }
    }
    .history-list {
        width: 100%;
        ul {
            display: flex;
            flex-wrap: wrap;
            align-items: center;
        }
        li {
            border-radius: 5px;
            font-size: 14px;
            color: #313131;
            padding: 0px 10px;
            margin: 0 15px 10px 0;
            border: 1px solid #999;
        }
    }
}
</style>
